<template>
  <div>
    <el-cascader v-model="value" style="width: 100%" :props="cascaderProps" />
  </div>
</template>

<script lang="ts" setup>
import { PropType, computed, reactive } from "vue";
import { VxeGlobalRendererHandles } from "vxe-pc-ui";
import CommonAPI from "@/api/common";
import type { CascaderNodePathValue, CascaderProps } from "element-plus";

const formatCascaderData = (data: any[], level: number) => {
  return data.map((item) => {
    return {
      value: item.id,
      label: item.name,
      leaf: level >= 3,
    };
  });
};

const cascaderProps: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    if (level === 0) {
      CommonAPI.getProvinceList().then((res) => {
        resolve(formatCascaderData(res, level));
      });
    } else {
      CommonAPI.getAreaList(node.value as number, level + 1).then((res) => {
        resolve(formatCascaderData(res, level));
      });
    }
  },
};

defineOptions({
  name: "VxeAreaSelect",
});

const value = computed<CascaderNodePathValue>({
  set(val) {
    const [provinceId, cityId, districtId, streetId] = val;
    const { params } = props;
    const { data } = params;
    data.provinceId = provinceId;
    data.cityId = cityId;
    data.districtId = districtId;
    data.streetId = streetId;
  },
  get() {
    const { params } = props;
    const { data } = params;
    return [data.provinceId, data.cityId, data.districtId, data.streetId];
  },
});

const props = defineProps({
  renderOpts: {
    type: Object as PropType<VxeGlobalRendererHandles.RenderFormItemContentOptions>,
    default: () => ({}),
  },
  params: {
    type: Object as PropType<VxeGlobalRendererHandles.RenderFormItemContentParams>,
    default: () => ({}),
  },
});

// const load = () => {
//   const { params } = props;
//   const { data } = params;
//   state.provinceId = data.provinceId;
//   state.cityId = data.cityId;
//   state.districtId = data.districtId;
//   state.streetId = data.streetId;
// };

// load();
</script>
